package com.heaboy.emaidemo1.util;

import com.heaboy.emaidemo1.config.MailConfig;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Properties;

@Component
public class MailSenderUtil {

    private static MailConfig staticMailConfig;

    @Autowired
    private MailConfig mailConfig;

    @PostConstruct
    public void init() {
        staticMailConfig = mailConfig;
    }

    //建立服务器的邮件连接，从而可以进行发送邮件
    public static Session getMailSession(){
        Properties properties = new Properties();
        properties.setProperty("mail.host", staticMailConfig.getMailHost());
        properties.setProperty("mail.smtp.auth", staticMailConfig.getMailSmtpAuth());
        // 添加QQ邮箱必要配置
        properties.setProperty("mail.smtp.port", staticMailConfig.getMailSmtpPort()); // 端口
        properties.setProperty("mail.smtp.starttls.enable", "true"); // 启用TLS加密（587端口需要）
        // 如果使用465端口，需替换为SSL配置：
        // properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        // properties.setProperty("mail.smtp.socketFactory.port", "465");

        Authenticator authenticator = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                // QQ邮箱用户名是完整邮箱地址，直接使用即可
                return new PasswordAuthentication(staticMailConfig.getUserName(), staticMailConfig.getPassWord());
            }
        };

        Session session = Session.getDefaultInstance(properties, authenticator);
        session.setDebug(true); // 可选：开启调试模式，便于排查问题
        return session;
    }

    /**
     * 指定一个人发送邮件，单个发送
     * @Param toEmailAddress 单个接受邮件的邮箱地址
     * @Param title 主题
     * @Param content 内容
     **/
    public static void sendMailTOSingleUser(String toEmailAddress,String title, String content){
        Session session = getMailSession();
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(staticMailConfig.getUserName()));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toEmailAddress));
            message.setRecipient(Message.RecipientType.CC, new InternetAddress(staticMailConfig.getUserName()));
            message.setSubject(title);
            message.setContent(content, "text/html;charset=UTF-8");
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 群发邮件,也可以只发一个人。可设置主题和邮件内容，无附件
     * @Param toEmailAddressArray 接受邮件的所有邮箱地址
     * @Param title 主题
     * @Param content 内容
     **/
    public static void sendMailToUserArray(ArrayList<String> toEmailAddressArrayList , String title, String content) {
        String[] toEmailAddressArray = toEmailAddressArrayList.toArray(new String[0]);
        Session session = getMailSession();
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(staticMailConfig.getUserName()));

            if (toEmailAddressArray != null) {
                Address[] toEmailRecipients = new InternetAddress[toEmailAddressArray.length];
                for (int i = 0; i < toEmailAddressArray.length; i++) {
                    toEmailRecipients[i] = new InternetAddress(toEmailAddressArray[i]);
                }
                message.setRecipients(MimeMessage.RecipientType.TO, toEmailRecipients);
            }

            message.setRecipient(Message.RecipientType.CC, new InternetAddress(staticMailConfig.getUserName()));
            message.setSubject(title);
            message.setContent(content, "text/html;charset=UTF-8");
            Transport.send(message);
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
}